import psutil
import pandas as pd
import time

# 函数systeminfo_write()读取系统的cpu，内存，磁盘，网络信息，生成并写入文件systeminfo.csv中
def systeminfo_write():
    # 时间戳
    timestamp = time.time()
    # CPU信息
    cpu_time = psutil.cpu_times()
    cpu_avg = psutil.getloadavg()
    cpu_stats = psutil.cpu_stats()
    # Memory信息
    mem = psutil.virtual_memory()
    men_swap = psutil.swap_memory()
    # Disk信息存储
    disk_usage = psutil.disk_usage('/')
    disk_io = psutil.disk_io_counters()
    # Internet信息存储
    net_io = psutil.net_io_counters()
    # 由 字典data1 生成 DataFrame类型df1
    data1 = {"时间戳": [timestamp], "CPU逻辑数量": [psutil.cpu_count()],
             "CPU物理核心": [psutil.cpu_count(logical=False)], "CPU使用率": [psutil.cpu_percent()],
             "CPU频率": [psutil.cpu_freq().current],
             "用户态运行时间": [cpu_time.user], "核心态运行时间": [cpu_time.system], "IO等待时间": [cpu_time.idle],
             "1min内平均负载": [cpu_avg[0]], "5min内平均负载": [cpu_avg[1]], "15min内平均负载": [cpu_avg[2]],
             "中断次数": [cpu_stats[1]], "软中断次数": [cpu_stats[2]], "系统调用次数": [cpu_stats[3]],
             "总内存": [mem.total / 1024 / 1024], "已用内存": [mem.used / 1024 / 1024],
             "空闲内存": [mem.free / 1024 / 1024], "使用内存占比": [mem.percent],
             "交换内存大小": [men_swap.total], "交换内存已用大小": [men_swap.used], "交换内存空闲大小": [men_swap.free],
             "交换内存使用占比": [men_swap.percent],
             "磁盘总空间": [disk_usage.total / 1024 / 1024], "磁盘已使用大小": [disk_usage.used / 1024 / 1024],
             "磁盘空闲大小": [disk_usage.free / 1024 / 1024],
             "磁盘使用占比": [disk_usage.percent], "读IO量": [disk_io.read_bytes / 1024 / 1024],
             "写IO量": [disk_io.write_bytes / 1024 / 1024],
             "磁盘读时间": [disk_io.read_time], "磁盘写时间": [disk_io.write_time]}
    df1 = pd.DataFrame(data1, index=["a"])
    # 记录所有网卡信息与流量 并接入df1
    io_stats = psutil.net_io_counters(pernic=True)
    for name, stats in io_stats.items():
        data_tem = {"网卡" + name + "发送数据大小": [stats.bytes_sent / 1024 / 1024],
                    "网卡" + name + "发送数据包数量": [stats.packets_sent],
                    "网卡" + name + "接收数据大小": [stats.bytes_recv / 1024 / 1024],
                    "网卡" + name + "接收数据包数量": [stats.packets_recv]}
        df_tem = pd.DataFrame(data_tem, index=["a"])
        df1 = pd.concat([df1, df_tem], axis=1)
    # 继写入文件systeminfo.csv中（隐藏 列表头与行索引）
    df1.to_csv("systeminfo.csv",mode='a+',index=False,header=False)

# 函数processinfo_write(cpupercent,mempercent)读取同一时间戳下系统中 cpu占用率大于cpupercent 或者 内存占用率大于mempercent 的所有进程，生成并写入文件processinfo.csv中
def processinfo_write(cpupercent,mempercent):
    # 进程的信息列表，便于之后构造字典

    # 时间戳
    timestamp = time.time()
    timestamp_list=[]
    # 进程名
    name_list=[]
    # 进程pid
    pid_list=[]
    # 进程cpu占用率
    cpupercent_list=[]
    # 进程内存占用率
    mempercent_list=[]
    # 进程状态
    status_list=[]
    # 进程读流量
    readbytes_list=[]
    # 进程写流量
    writebytes_list=[]
    # vms大小
    vms_list=[]
    # rss大小
    rss_list=[]
    # 使用线程数
    threads_list = []
    # 进程创建时间戳
    createtime_list = []
    # 遍历进程pid列表，寻找满足条件的进程存入列表
    for i in psutil.pids():
        if psutil.pid_exists(i):
            p = psutil.Process(i)
            if p.cpu_percent() >= cpupercent or p.memory_percent() >= mempercent:
                timestamp_list.append(timestamp)
                name_list.append(p.name())
                pid_list.append(i)
                cpupercent_list.append(p.cpu_percent())
                mempercent_list.append(p.memory_percent())
                status_list.append(p.status())
                readbytes_list.append(p.io_counters().read_bytes)
                writebytes_list.append(p.io_counters().write_bytes)
                vms_list.append(p.memory_info().vms)
                rss_list.append(p.memory_info().rss)
                threads_list.append(p.num_threads())
                createtime_list.append(p.create_time())
    # 构建字典以构建DataFrame类型的df，继写入文件processinfo.csv
    data={"时间戳":timestamp_list,
    "进程名":name_list,
    "进程号":pid_list,
    "cpu占用率":cpupercent_list,
    "内存占用率":mempercent_list,
    "状态":status_list,
    "读取字节数":readbytes_list,
    "写入字节数":writebytes_list,
    "vms":vms_list,
    "rss":rss_list,
    "使用线程数":threads_list,
    "创建时间":createtime_list}
    df = pd.DataFrame(data)
    df.to_csv("processinfo.csv",mode='a+',index=False,header=False)

# 每隔timeset秒监测一次系统信息（cpu，内存，磁盘，网络），重复监测num次
def systeminfo_flicker(timeset,num):
    for i in range(0,num):
        systeminfo_write()
        time.sleep(timeset)

# 每隔timeset秒监测一次进程信息，重复监测num次
def processinfo_flicker(timeset,num,cpupercent,mempercent):
    for i in range(0,num):
        processinfo_write(cpupercent,mempercent)
        time.sleep(timeset)

# 测试
if __name__ == "__main__":
    systeminfo_flicker(1,10)
    processinfo_flicker(1,10,0.1,0.5)
